package src.main.java.com.pms.gui.dialog.appointment;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import src.main.java.com.pms.service.AppointmentService;

public class EditAppointmentDialog extends JDialog {
    private JCheckBox bathCheckBox;
    private JCheckBox vaccineCheckBox;
    private JCheckBox cremationCheckBox;
    private AppointmentService appointmentService;
    private int petId;

    public EditAppointmentDialog(AppointmentListDialog parent, int petId, boolean hasBathAppointment, boolean hasVaccineAppointment, boolean hasCremationAppointment) {
        super(parent, "编辑预约", true);
        this.petId = petId;
        this.appointmentService = new AppointmentService();
        initComponents(hasBathAppointment, hasVaccineAppointment, hasCremationAppointment);
    }

    private void initComponents(boolean hasBathAppointment, boolean hasVaccineAppointment, boolean hasCremationAppointment) {
        setSize(400, 200);
        setLocationRelativeTo(getParent());

        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);

        // 洗澡预约
        gbc.gridx = 0;
        gbc.gridy = 0;
        bathCheckBox = new JCheckBox("洗澡预约");
        bathCheckBox.setSelected(hasBathAppointment);
        panel.add(bathCheckBox, gbc);

        // 疫苗预约
        gbc.gridx = 0;
        gbc.gridy = 1;
        vaccineCheckBox = new JCheckBox("疫苗预约");
        vaccineCheckBox.setSelected(hasVaccineAppointment);
        panel.add(vaccineCheckBox, gbc);

        // 火葬预约
        gbc.gridx = 0;
        gbc.gridy = 2;
        cremationCheckBox = new JCheckBox("火葬预约");
        cremationCheckBox.setSelected(hasCremationAppointment);
        panel.add(cremationCheckBox, gbc);

        // 保存按钮
        JButton saveButton = new JButton("保存");
        saveButton.addActionListener(new SaveActionListener());

        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.gridwidth = 2;
        panel.add(saveButton, gbc);

        add(panel);
    }

    private class SaveActionListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                appointmentService.updateAppointment(petId, "bath", bathCheckBox.isSelected());
                appointmentService.updateAppointment(petId, "vaccine", vaccineCheckBox.isSelected());
                appointmentService.updateAppointment(petId, "cremation", cremationCheckBox.isSelected());
                JOptionPane.showMessageDialog(EditAppointmentDialog.this, "预约更新成功", "成功", JOptionPane.INFORMATION_MESSAGE);
                dispose();
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(EditAppointmentDialog.this, "更新预约失败：" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
}
